<template>
  <div class="category">
    <div class="search">
      <el-form ref="searchForm" v-loading="listLoading" :model="searchForm" inline>
        <!-- <el-form-item label="用户ID" prop="id">
          <el-input
            v-model.trim="searchForm.id"
            placeholder="用户ID"
            class="input"
            clearable
          />
        </el-form-item> -->

        <!-- <el-form-item label="用户状态：" prop="status">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
          >
            <el-option label="隐藏" value="0" />
            <el-option label="正常" value="1" />
          </el-select>
        </el-form-item> -->

        <el-form-item label="用户昵称" prop="nickName">
          <el-input v-model.trim="searchForm.nickName" placeholder="用户昵称" class="input" clearable />
        </el-form-item>

        <!-- <el-form-item>
          <el-button type="primary" size="medium" @click="searchData">
            搜索
          </el-button>
          <el-button type="primary" size="medium" @click="resetSearchData">
            重置
          </el-button>
        </el-form-item> -->
      </el-form>
    </div>

    <div class="app-container">
      <el-table v-loading="listLoading"
        :data="filter().slice((searchForm.page - 1) * searchForm.pageSize, searchForm.page * searchForm.pageSize)"
        element-loading-text="Loading" border fit highlight-current-row>

        <el-table-column label="用户名称" align="center">
          <template slot-scope="scope">
            {{ scope.row.nickName }}
          </template>
        </el-table-column>
        <el-table-column label="用户手机" align="center">
          <template slot-scope="scope">
            {{ scope.row.phone }}
          </template>
        </el-table-column>
        <el-table-column label="用户密码" align="center">
          <template slot-scope="scope">
            {{ md5(scope.row.password) }}
          </template>
        </el-table-column>
        <el-table-column label="邀请人" align="center">
          <template slot-scope="scope">
            {{ yaoqingren(scope.row.parent) }}
          </template>
        </el-table-column>
        <el-table-column label="冻结金额" align="center">
          <template slot-scope="scope">
            {{ scope.row.dongjie }}
          </template>
        </el-table-column>
        <el-table-column label="未结算金额" align="center">
          <template slot-scope="scope">
            {{ scope.row.weijiesuan }}
          </template>
        </el-table-column>
        <el-table-column label="打手押金" align="center">
          <template slot-scope="scope">
            {{ scope.row.yajin }}
          </template>
        </el-table-column>
        <!-- <el-table-column class-name="status-col" label="在线状态" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status | statusFilter">{{
              scope.row.status | statusFilterText
            }}</el-tag>
          </template>
        </el-table-column> -->
        <el-table-column label="禁用/启用" align="center">
          <template slot-scope="scope">

              <el-button v-if="scope.row.stop" size="mini" type="text" @click="palyerStop(scope.row)">禁用</el-button>
              <el-button v-if="!scope.row.stop" size="mini" type="text" @click="palyerStop(scope.row)">启用</el-button>

            <!-- <el-button size="mini" type="danger" @click="handleDelete(scope.row.id)">删除</el-button> -->
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">

            <el-button size="mini" type="text" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="text" @click="fakuan(scope.row)">罚款</el-button>
            <el-button size="mini" type="text" @click="jiesuan(scope.row)">结算</el-button>
            <!-- <el-button size="mini" type="danger" @click="handleDelete(scope.row.id)">删除</el-button> -->
          </template>
        </el-table-column>
      </el-table>

      <el-dialog title="罚款" :visible.sync="dialogFormVisible">
        <el-form :model="dealobj">
          <el-form-item label="罚款金额">
            <el-input v-model="dealobj.value" type="number"></el-input>
          </el-form-item>
          <el-form-item label="罚款原因">
            <el-input v-model="dealobj.yuanyin"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="submit">确 定</el-button>
        </div>
      </el-dialog>

      <el-dialog title="打手结算" :visible.sync="qrDialogVisible" width="30%" center>
        <div>打手收款码</div>
        <div>{{ '打手：' + item.nickName }}</div>
        <div style="height: 170px;">
          <img v-if="item.qr" :src="item.qr" style="height: 100%;" />
          <div v-if="!item.qr">没有上传收款码</div>
        </div>
        <span>支付金额：￥{{ Number(item.weijiesuan) }}</span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="qrDialogVisible = false">取消支付</el-button>
          <el-button type="primary" @click="orderPay" v-if="item.qr">已支付</el-button>
        </span>
      </el-dialog>

      <div class="pagination">
        <el-pagination background :current-page.sync="searchForm.page" layout="total, prev, pager, next"
          :total="filter().length" @current-change="handleCurrentChange" />
      </div>
    </div>
  </div>
</template>

<script>
import { getUserList, deleteUser } from '@/api/user'
import userApi from '@/plugins/api/user'
import dealApi from '@/plugins/api/deal'
import { fuzzyMatch } from '@/plugins/utils/filterArray'
import crypto from 'crypto'
import configApi from '@/plugins/api/config'
import {plugins} from "../../../postcss.config";
export default {
  name: 'UserList',
  computed: {
    plugins() {
      return plugins
    }
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        0: 'danger',
        1: 'success'
      }
      return statusMap[status]
    },
    statusFilterText(status) {
      const statusMap = {
        0: '禁用',
        1: '正常'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      list: null,
      listLoading: true,
      qrDialogVisible: false,
      count: 0,
      item: {},
      searchForm: {
        nickName: '',
        phone: '',
        role: 2,
        page: 1,
        pageSize: 10
      },
      dialogFormVisible: false,
      dealobj: {
        userId: null,
        value: 0,
        createTime: null,
        type: 3,
        yuanyin: ''
      },
      users: [],
      yajin: 0
    }
  },
  mounted() {
    this.getUsers()
    this.fetchData()
  },
  methods: {
    // 禁止用户操作
    async palyerStop(row) {

      const p = row
      p.stop = !p.stop
      console.log(p)
      const res = await userApi.update(p)
      console.log(res)
      if (res.code === 200) {
        this.$message.success('操作成功')
        this.getUsers()
      }else {
        this.$message.error(res.msg)
      }
    },

    yaoqingren(id) {
      if (id) {
        const user = this.users.find(item => item.id === id)
        return user ? user.nickName : '暂无邀请人'
      }
      return '暂无邀请人'
    },
    filter() {
      return fuzzyMatch(this.list, this.searchForm)
    },

    md5(text) {
      return crypto.createHash('md5').update(text).digest('hex')
    },

    async getUsers() {
      const res = await userApi.all()
      if (res.code === 200) {
        this.users = res.data
      } else {
        this.$message.error(res.msg)
      }
    },

    // 获取用户信息
    async fetchData() {
      await this.getConfig()
      const that = this
      try {
        this.listLoading = true
        const res = await userApi.all()
        console.log('res -> ', res);
        const players = res.data.filter(item => item.role === 2)
        const dealRes = await dealApi.list()
        let deals = dealRes.code === 200 ? dealRes.data : []
        for (let i = 0; i < players.length; i++) {
          players[i].deals = deals.filter(item => item.userId === players[i].id)
        }

        for (let k = 0; k < players.length; k++) {
          players[k] = that.initPlayerBalance(players[k])
        }

        console.log('players -> ', players);
        this.list = players

      } catch (err) {
        console.log(err)
      } finally {
        this.listLoading = false
      }
    },

    async getConfig() {
      const that = this
      const res = await configApi.list()
      if (res.code === 200) {
        console.log('res.data -> ', res.data);
        const config = res.data.find(item => item.name === 'yajin')
        console.log('config -> ', config);
        this.yajin = config.value
      }
    },

    initPlayerBalance(item) {
      item.dongjie = 0
      item.weijiesuan = 0
      item.yajinValue = JSON.parse(JSON.stringify(item.yajin))
      let fakuanValue = 0
      const yongjin = item.deals.filter(item => item.type === 2 && !item.status)
      const fakuan = item.deals.filter(item => item.type === 3 && !item.status)

      for (let j = 0; j < fakuan.length; j++) {
        fakuanValue = Number(fakuan[j].value) + fakuanValue
      }
      if (Number(fakuanValue) * -1) {
        if (item.dongjie > 0 && item.dongjie >= Number(fakuanValue) * -1) {
          item.dongjie = item.dongjie + Number(fakuanValue)
          fakuanValue = 0
        } else if (item.dongjie > 0 && item.dongjie <= Number(fakuanValue) * -1) {
          item.dongjie = 0
          fakuanValue = Number(fakuanValue) + item.dongjie
        }
      }

      if (Number(fakuanValue) * -1) {
        if (item.weijiesuan > 0 && item.weijiesuan >= Number(fakuanValue) * -1) {
          item.weijiesuan = item.weijiesuan + Number(fakuanValue)
          fakuanValue = 0
        } else if (item.weijiesuan > 0 && item.weijiesuan <= Number(fakuanValue) * -1) {
          item.weijiesuan = 0
          fakuanValue = Number(fakuanValue) + item.weijiesuan
        }
      }

      if (Number(fakuanValue) * -1) {
        item.yajin = Number(item.yajin) + Number(fakuanValue)
      }

      for (let i = 0; i < yongjin.length; i++) {
        if (item.yajin <= this.yajin) {
          if (item.yajin + Number(yongjin[i].value) <= this.yajin) {
            item.yajin = Number(yongjin[i].value) + item.yajin
          } else {
            const yj = yongjin[i].value - (this.yajin - item.yajin)
            item.yajin = this.yajin
            if (new Date().getTime() >= yongjin[i].jiesuanTime) {
              item.weijiesuan = Number(yj) + item.weijiesuan
            } else {
              item.dongjie = Number(yj) + item.dongjie
            }
          }

        } else {
          if (new Date().getTime() >= yongjin[i].jiesuanTime) {
            item.weijiesuan = Number(yongjin[i].value) + item.weijiesuan
          } else {
            item.dongjie = Number(yongjin[i].value) + item.dongjie
          }
        }


      }

      // item.yajinValue = item.yajin

      console.log(item.nickName + ' -> ', `冻结：${item.dongjie}, 未结算${item.weijiesuan}`);

      return item

    },

    jiesuan(row) {
      this.item = row
      this.qrDialogVisible = true
    },

    async orderPay() {
      const that = this
      const deals = this.item.deals.filter(item => !item.status)
      console.log(deals.filter(item => item.type === 3));
      await that.jiesuanOrderpay(deals)
      console.log(that.item.yajinValue);
    },

    jiesuanOrderpay(arr) {
      const that = this
      let index = 0
      const payItem = async (item) => {
        if (arr.length - 1 >= index && arr.length > 0) {
          item.status = true
          const res = await that.dealItemJiesuan(item)
          if (res) {
            index += 1
            payItem(arr[index])
            if (index === arr.length - 1) {
              that.item.yajin = that.item.yajinValue
              const ures = await userApi.update(that.item)
              if (ures.code === 200) {
                that.$message.success('结算成功')
                that.qrDialogVisible = false
                that.fetchData()
              }
            }
          } else {
            that.$message.error('结算出错，请重新结算')
          }
        }
      }
      payItem(arr[index])
    },

    async dealItemJiesuan(v) {
      v.status = true
      const res = await dealApi.modify(v)
      if (res.code === 200) {
        return true
      }
      return false
    },

    // 跳转编辑
    handleEdit(row) {
      localStorage.setItem('huiyuan', JSON.stringify(row))
      this.$router.push('/player/edit')
    },
    fakuan(row) {
      this.dealobj.userId = row.id
      this.dialogFormVisible = true
    },

    async submit() {
      const that = this
      console.log(that.dealobj);
      const dealobj = {
        userId: that.dealobj.userId,
        value: `-${that.dealobj.value}`,
        type: 3,
        createTime: new Date().getTime(),
        status: false,
        yuanyin: that.dealobj.yuanyin
      }
      const fakuanres = await dealApi.modify(dealobj)
      if (fakuanres.code === 200) {
        that.$message.success('罚款成功')
        that.dialogFormVisible = false
      } else {
        that.$message.error(fakuanres.msg)
      }
    },
    // 删除用户
    handleDelete(id) {
      try {
        this.$msgbox
          .confirm('确定需要删除这个用户吗', '提示', {
            confirmButtonText: '删除',
            cancelButtonText: '取消',
            type: 'error'
          })
          .then(async () => {
            const r = await deleteUser({ id })
            this.$message.success(r.msg)
            await this.fetchData()
          })
      } catch (err) {
        this.$message.error(err)
      }
    },
    // 搜索
    searchData() {
      this.searchForm.page = 1
      this.searchForm.role = 2
    },
    // 点击页面
    handleCurrentChange(page) {
      this.searchForm.page = page
      // this.fetchData()
    },
    // 重置表单
    resetSearchData() {
      this.$refs['searchForm'].resetFields()
      this.fetchData()
    }
  }
}
</script>

<style scoped lang="scss">
.category {
  box-sizing: border-box;
  margin: 24px;
}

.search {
  box-sizing: border-box;
  border-bottom: 1px solid #f0f0f0;
}

.pagination {
  display: flex;
  justify-content: center;
  margin: 24px 0;
}
</style>
